<?php

namespace app\index\controller;

use app\admin\model\Engineer;
use app\admin\model\Order;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;

/**
 * 工程师中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'third'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
        $this->model = new Engineer();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }

        //监听登录登出事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 工程师中心
     */
    public function index()
    {
        // 获取当前登录工程师信息
        $engineerId = $this->auth->id;
        $engineer = $this->model->where('id', $engineerId)->find();
        
        if (!$engineer) {
            $this->error('工程师信息不存在');
        }

        // 使用原生SQL查询带有中文字段的工单数据
        $engineerName = $engineer['name'];
        $orders = Db::query("SELECT * FROM `fa_order` WHERE `配送工程师` = '{$engineerName}' ");
        //return json($orders);
        $this->view->assign('title', __('Engineer center'));
        $this->view->assign('engineer', $engineer);
        $this->view->assign('orders', $orders);
        return $this->view->fetch();
    }

    /**
     * 工程师登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ?: url('user/index'));
        }
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $password = $this->request->post('password', '', null);
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            
            $rule = [
                'mobile'    => 'require|regex:/^1\d{10}$/',
                'password'  => 'require|length:6,50',
                '__token__' => 'require|token',
            ];

            $msg = [
                'mobile.require'   => '手机号不能为空',
                'mobile'           => '手机号格式不正确',
                'password.require' => '密码不能为空',
                'password.length'  => '密码长度必须在6-50个字符之间',
            ];
            
            $data = [
                'mobile'    => $mobile,
                'password'  => $password,
                '__token__' => $token,
            ];
            
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            
            // 在fa_engineer表中查找用户
            $engineer = $this->model->where('mobile', $mobile)->find();
            
            if (!$engineer) {
                $this->error('账号不存在', null, ['token' => $this->request->token()]);
            }
            
            // 验证密码（明文比较）
            if ($engineer['password'] !== $password) {
                $this->error('密码不正确', null, ['token' => $this->request->token()]);
            }
            
            // 登录成功，设置会话
            $this->auth->direct($engineer['id']);
            
            $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
        }
        
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->token();
            //退出本站
            $this->auth->logout();
            $this->success(__('Logout successful'), url('user/index'));
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $engineerId = $this->auth->id;
        $engineer = $this->model->where('id', $engineerId)->find();
        
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            // 验证参数
            $validate = new Validate([
                'name'  => 'require|length:2,50',
                'mobile' => 'require|regex:/^1\d{10}$/',
                'area'  => 'require',
            ]);
            
            if (!$validate->check($params)) {
                $this->error($validate->getError());
            }
            
            // 更新工程师信息
            $updateData = [
                'name'       => $params['name'],
                'mobile'     => $params['mobile'],
                'area'       => $params['area'],
                'tags'       => isset($params['tags']) ? $params['tags'] : $engineer['tags'],
                'updatetime' => time(),
            ];
            
            $result = $engineer->save($updateData);
            
            if ($result !== false) {
                $this->success('资料更新成功');
            } else {
                $this->error('资料更新失败');
            }
        }
        
        $this->view->assign('title', __('Profile'));
        $this->view->assign('engineer', $engineer);
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword", '', null);
            $newpassword = $this->request->post("newpassword", '', null);
            $renewpassword = $this->request->post("renewpassword", '', null);
            $token = $this->request->post('__token__');
            
            $rule = [
                'oldpassword'   => 'require|regex:\S{6,50}',
                'newpassword'   => 'require|regex:\S{6,50}',
                'renewpassword' => 'require|regex:\S{6,50}|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }

            $engineerId = $this->auth->id;
            $engineer = $this->model->where('id', $engineerId)->find();
            
            // 验证旧密码（明文比较）
            if ($oldpassword != $engineer['password']) {
                $this->error('原密码不正确', null, ['token' => $this->request->token()]);
            }
            
            // 更新密码（明文存储）
            $result = $engineer->save([
                'password'   => $newpassword,
                'updatetime' => time(),
            ]);
            
            if ($result !== false) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error('密码修改失败', null, ['token' => $this->request->token()]);
            }
        }
        
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    /**
     * 附件管理
     */
    public function attachment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $where = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/(\/|\,|\*)/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = array_filter(explode(',', $filterArr['mimetype']));
                    foreach ($mimetypeArr as $index => $item) {
                        $query->whereOr('mimetype', 'like', '%' . str_replace("/*", "/", $item) . '%');
                    }
                };
            } elseif (isset($filterArr['mimetype'])) {
                $where['mimetype'] = ['like', '%' . $filterArr['mimetype'] . '%'];
            }

            if (isset($filterArr['filename'])) {
                $where['filename'] = ['like', '%' . $filterArr['filename'] . '%'];
            }

            if (isset($filterArr['createtime'])) {
                $timeArr = explode(' - ', $filterArr['createtime']);
                $where['createtime'] = ['between', [strtotime($timeArr[0]), strtotime($timeArr[1])]];
            }
            $search = $this->request->get('search');
            if ($search) {
                $where['filename'] = ['like', '%' . $search . '%'];
            }

            $model = new Attachment();
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $total = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->count();

            $list = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $mimetype = $this->request->get('mimetype', '');
        $mimetype = substr($mimetype, -1) === '/' ? $mimetype . '*' : $mimetype;
        $this->view->assign('mimetype', $mimetype);
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
        return $this->view->fetch();
    }

    /**
     * 更新工程师备注
     */
    public function updateEngineerNote()
    {
        if ($this->request->isAjax()) {
            $orderId = $this->request->post('order_id');
            $engineerNote = $this->request->post('engineer_note');
            
            // 验证工单是否存在
            $order = Db::name('order')->where('id', $orderId)->find();
            if (!$order) {
                return json(['code' => 0, 'msg' => '工单不存在']);
            }
            
            // 验证是否为当前工程师的工单
            $engineerName = $this->auth->name;
            if ($order['配送工程师'] != $engineerName) {
                return json(['code' => 0, 'msg' => '没有权限修改该工单']);
            }
            
            // 更新备注
            $result = Db::name('order')->where('id', $orderId)->update(['工程师备注' => $engineerNote]);
            
            if ($result !== false) {
                return json(['code' => 1, 'msg' => '备注更新成功']);
            } else {
                return json(['code' => 0, 'msg' => '备注更新失败']);
            }
        }
        
        return json(['code' => 0, 'msg' => '非法请求']);
    }
}
